package com.huilian.iotbox.mqtt.server.base.handler.penetrate.vendmach;

import com.huilian.iotbox.data.common.RedisKey;
import com.huilian.iotbox.data.dto.CommodityStockRecordDto;
import com.huilian.iotbox.data.dto.CommodityStockRecordItemDto;
import com.huilian.iotbox.data.dto.DisplayRackItemDto;
import com.huilian.iotbox.data.enums.CommodityStockRecordFirstTypeEnum;
import com.huilian.iotbox.data.enums.CommodityStockRecordSecondTypeEnum;
import com.huilian.iotbox.data.enums.CommodityStockRecordStatusEnum;
import com.huilian.iotbox.data.vo.DeviceVo;
import com.huilian.iotbox.data.vo.DisplayRackItemVo;
import com.huilian.iotbox.mqtt.server.base.handler.penetrate.PenetrateHandlerStrategy;
import com.huilian.iotbox.mqtt.server.base.service.*;
import com.huilian.tool.weixin.service.WXSendMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service("penetrateHandlerServiceC914")
public class LatticeShipmentC914FHandler implements PenetrateHandlerStrategy {

    @Value("${huilian.iot.productKey}")
    private String productKey;
    @Resource
    private DisplayRackItemService displayRackItemService;
    @Resource
    private DeviceService deviceService;
    @Resource
    private CommodityStockRecordService commodityStockRecordService;
    @Resource
    private CommodityStockRecordItemService commodityStockRecordItemService;
    @Resource
    private WXSendMessageService wxSendMessageService;
    @Resource
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    @Override
    public void process(String content, String deviceNo, Integer positionId) throws Exception {
//        AA 1E 02 C9 14 00 00 00 00 00 09 27 D2 01 08 01 01 01 01 01 01 01 01 05 07 E8 07 0C 09 31 27 CA DD
        DeviceVo oneDeviceByDeviceNo = deviceService.findOneDeviceByDeviceNo(deviceNo);
        log.info("{}设备进入电磁格子机补货:{}",deviceNo,content);
        //补货数量
        int quantity = Integer.parseInt(content.substring(29, 30));
        //获取电量
        int power = Integer.parseInt(content.substring(content.length()- 20,content.length() - 18),16);
        this.batteryNotification(oneDeviceByDeviceNo,power);
        //获取补货操作时间
        int year = Integer.parseInt(content.substring(content.length()- 18,content.length() - 14),16);
        int moon = Integer.parseInt(content.substring(content.length()- 14,content.length() - 12),16);
        int day = Integer.parseInt(content.substring(content.length()- 12,content.length() - 10),16);
        int hour = Integer.parseInt(content.substring(content.length()- 10,content.length() - 8),16);
        int point = Integer.parseInt(content.substring(content.length()- 8,content.length() - 6),16);
        int second = Integer.parseInt(content.substring(content.length()- 6,content.length() - 4),16);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = year +""+ (moon<10?"0"+moon:moon) +""+ (day<10?"0"+day:day) +""+ (hour<10?"0"+hour:hour) +""+ (point<10?"0"+point:point) +""+ (second<10?"0"+second:second);
        //格式化补货操作时间
        Date processingTime = dateFormat.parse(time);
        int starting = 29;
        int finish   = 30;
        for (int i = 0; i < quantity; i++) {
            int cargoLane = Integer.parseInt(content.substring(starting+=2, finish+=2));
            log.info("货道:{},补货数量:{}",i+1,cargoLane);
            if (cargoLane != 0){
                DisplayRackItemDto displayRackItemDto = new DisplayRackItemDto();
                displayRackItemDto.setDeviceId(oneDeviceByDeviceNo.getId());
                displayRackItemDto.setStatus(true);
                displayRackItemDto.setHierarchy(1);  //现在只有1层8个货道  所以层先写死1
                displayRackItemDto.setFreightLane(i + 1);
                displayRackItemDto.setStock(cargoLane);
                displayRackItemDto.setIsDelete(false);
                DisplayRackItemVo displayRackItemVo = displayRackItemService.findDisplayRackItemByHierarchyAndFreightLane(displayRackItemDto);
                log.info("货道信息{}",displayRackItemVo);
                if (!StringUtils.isEmpty(displayRackItemVo) && displayRackItemVo.getStock() != cargoLane && !StringUtils.isEmpty(displayRackItemVo.getCommodityId())){
                    log.info("满足补货条件");
                    CommodityStockRecordDto commodityStockRecord = new CommodityStockRecordDto();
                            commodityStockRecord.setUserId(displayRackItemVo.getUserId());
                            commodityStockRecord.setMerchantStoreId(displayRackItemVo.getMerchantStoreId());
                            commodityStockRecord.setDeviceId(oneDeviceByDeviceNo.getId());
                            commodityStockRecord.setDescription("蓝牙格子机同步库存");
                            commodityStockRecord.setStatus(CommodityStockRecordStatusEnum.COMPLETED.getCode());
                            commodityStockRecord.setOperationUserId(displayRackItemVo.getUserId());
                            commodityStockRecord.setInDisplayRackId(displayRackItemVo.getDisplayRackId());
                            commodityStockRecord.setFirstType(CommodityStockRecordFirstTypeEnum.INTO_STOCK_ORDER.getCode());
                            commodityStockRecord.setSecondaryType(CommodityStockRecordSecondTypeEnum.VENDING_MACHINE_STORE_RECEIPT.getCode());
                            commodityStockRecord.setProcessingTime(processingTime);
                    commodityStockRecordService.add(commodityStockRecord);
                    CommodityStockRecordItemDto commodityStockRecordItem = new CommodityStockRecordItemDto();
                            commodityStockRecordItem.setCommodityStockRecordId(commodityStockRecord.getId());
                            commodityStockRecordItem.setCommodityId(displayRackItemVo.getCommodityId());
                            commodityStockRecordItem.setQuantity(displayRackItemDto.getStock());
                            commodityStockRecordItem.setHierarchy(displayRackItemVo.getHierarchy());
                            commodityStockRecordItem.setFreightLane(displayRackItemVo.getFreightLane());
                            commodityStockRecordItem.setCostPrice(displayRackItemVo.getCostPrice());
                            commodityStockRecordItem.setRetailPrice(displayRackItemVo.getRetailPrice());
                            commodityStockRecordItem.setStockBefore(displayRackItemVo.getStock());
                            commodityStockRecordItem.setStockAfter(displayRackItemDto.getStock());
                            commodityStockRecordItem.setCostPriceBefore(displayRackItemVo.getCostPrice());
                            commodityStockRecordItem.setCostPriceAfter(displayRackItemVo.getCostPrice());
                            commodityStockRecordItem.setRetailPriceBefore(displayRackItemVo.getRetailPrice());
                            commodityStockRecordItem.setRetailPriceAfter(displayRackItemVo.getRetailPrice());
                            commodityStockRecordItem.setProcessingTime(processingTime);
                            commodityStockRecordItem.setRemark("蓝牙格子机同步库存");
                    commodityStockRecordItemService.add(commodityStockRecordItem);

                    displayRackItemService.updateStock(displayRackItemDto);
                }else{
                    log.info("不满足补货条件");
                }
            }
        }
    }
    /**
     * 低电量通知
     */
    private void batteryNotification(DeviceVo deviceVo,int power) throws Exception {
        if (power <= 2){
            String key = String.format(RedisKey.LOW_BATTERY_RECORD,deviceVo.getDeviceNo());
            boolean isExist = Boolean.TRUE.equals(redisCacheTemplate.hasKey(key));
            if (!isExist){
                //设置24小时过期,缓存没过期就不再发送通知
                redisCacheTemplate.opsForValue().set(key,power,24, TimeUnit.HOURS);

                int percentagePerBar = 20;
                String residualCurrent = (int) Math.floor(power * percentagePerBar) + "%";
                wxSendMessageService.sendVendingPowerMessage(deviceVo.getDeviceNo(),residualCurrent,new Date(),deviceVo.getUserId(),deviceVo.getMerchantStoreId(),deviceVo.getStoreName());
            }
        }
    }
}
